# Requires: Python on the build machine (no need in target), optional UPX in PATH
# Usage:
#   powershell -ExecutionPolicy Bypass -File .\build.ps1

$ErrorActionPreference = "Stop"

function Get-Python {
    $venvPy = Join-Path (Resolve-Path ".").Path ".venv/Scripts/python.exe"
    if (Test-Path $venvPy) { return $venvPy }
    return "python"
}

$Python = Get-Python

function Ensure-Pip {
    try {
        & $Python -m pip --version 2>$null | Out-Null
    } catch {
        Write-Host "Bootstrapping pip via ensurepip..."
        & $Python -m ensurepip --upgrade
    }
    try {
        & $Python -m pip --version | Out-Null
    } catch {
        throw "pip is not available after ensurepip. Please install pip for $Python"
    }
    # Upgrade basic tooling
    & $Python -m pip install --upgrade pip setuptools wheel | Out-Null
}

function Ensure-PyInstaller {
    try {
        & $Python -m PyInstaller --version 2>$null | Out-Null
    } catch {
        Write-Host "Installing PyInstaller..."
        & $Python -m pip install --upgrade pyinstaller | Out-Null
    }
    & $Python -m PyInstaller --version | Write-Host
}

function Ensure-UPX {
    try {
        $upxCmd = Get-Command upx -ErrorAction Stop
        return (Split-Path $upxCmd.Path)
    } catch {
        Write-Host "UPX not found - attempting to download locally (./.tools/upx) ..."
        $toolsDir = Join-Path (Resolve-Path ".").Path ".tools"
        if (-not (Test-Path $toolsDir)) { New-Item -ItemType Directory -Path $toolsDir | Out-Null }
        $upxDir = Join-Path $toolsDir "upx"
        if (-not (Test-Path $upxDir)) { New-Item -ItemType Directory -Path $upxDir | Out-Null }
        $upxUrl = "https://github.com/upx/upx/releases/download/v4.2.4/upx-4.2.4-win64.zip"
        $zipPath = Join-Path $toolsDir "upx.zip"
        Invoke-WebRequest -Uri $upxUrl -OutFile $zipPath -UseBasicParsing
        Expand-Archive -Path $zipPath -DestinationPath $upxDir -Force
        Remove-Item $zipPath -Force
        $extracted = Get-ChildItem $upxDir | Where-Object { $_.PSIsContainer -and $_.Name -like "upx-*" } | Select-Object -First 1
        if ($null -eq $extracted) { throw "Failed to extract UPX" }
        $binDir = $extracted.FullName
        $env:Path = "$binDir;$env:Path"
        return $binDir
    }
}

Ensure-Pip
Ensure-PyInstaller
$UpxPath = Ensure-UPX

# Aggressive UPX compression flags
if ($UpxPath) { $env:UPXFLAGS = "-9 --lzma" }

# Build options
$AppName = "StardewModTranslator"
$Entry   = "translate_mods.py"
$DistDir = "dist"
$BuildDir = "build"

# Clean previous
if (Test-Path $DistDir) { Remove-Item -Recurse -Force $DistDir }
if (Test-Path $BuildDir) { Remove-Item -Recurse -Force $BuildDir }

# Compose pyinstaller args
$pyiArgs = @(
    "--clean",
    "--onefile",
    "--name", $AppName,
    "--noconsole",         # 去掉控制台窗口，可减少体积
    "--optimize", "2"
)

# Exclude heavy unused modules to reduce size
$excludes = @("tkinter", "numpy", "pandas", "pytest", "matplotlib", "scipy")
foreach ($m in $excludes) { $pyiArgs += @("--exclude-module", $m) }

# Enable UPX if present/installed
if ($UpxPath -and (Test-Path $UpxPath)) {
    Write-Host "UPX enabled at $UpxPath (flags: $env:UPXFLAGS)"
    $pyiArgs += @("--upx-dir", $UpxPath)
} else {
    Write-Host "UPX still not available - skipping compression (optional)."
}

# Run PyInstaller via the chosen Python (use argument splatting)
Write-Host "Running: $Python -m PyInstaller $($pyiArgs -join ' ') $Entry"
& $Python -m PyInstaller @pyiArgs $Entry

Write-Host "`nBuild finished. Output: .\\dist\\$AppName.exe"
Write-Host "Place config.json next to the exe (external config)."
